package com.computer.fundamentals.algorithm;

import java.util.HashMap;
import java.util.Map;

public class Crontab {

    class Quartz extends Thread{
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                for (Integer key : map.keySet()) {
                    if (System.currentTimeMillis() - map.get(key).startTime >= map.get(key).time) {
                        map.remove(key);
                    }
                }
            }
        }
    }

    static class Node {
        Integer val;
        Long startTime;
        Integer time;

        public Node(Integer val, Integer time) {
            this.val = val;
            this.time = time;
            this.startTime = System.currentTimeMillis();
        }
    }

    public Map<Integer, Node> map;
    public Quartz quartz;

    public Crontab() {
        this.map = new HashMap<>();
        this.quartz = new Quartz();
    }

    /**
     * 删除
     */
    public void remove(Integer key) {
        map.remove(key);
    }

    /**
     * 定时
     */
    public void quart() {
        System.out.println("定时任务进行中！");
        quartz.start();
    }

    /**
     * 插入数据
     */
    public void set(Integer key, Integer value, Integer time) {
        map.put(key, new Node(value, time));
    }

    /**
     * 获取数据
     */
    public Integer get(Integer key) {
        if (key == null) {
            throw new RuntimeException("key不可以为空！");
        }
        if (map.get(key) == null) {
            throw new RuntimeException("不存在该数据！");
        }
        Node node = map.get(key);
        if (node.time == 0) {
            remove(key);
            return null;
        }
        return node.val;
    }

    /**
     * 测试
     */
    public static void main(String[] args) {
        Crontab crontab = new Crontab();
        crontab.quart();
    }
}
